/* 
 * Copyright 2010 Ziya Guven Koylu, Ozge Koylu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.koylu.caffein.validator;

import java.io.InputStream;

import org.apache.commons.digester.Digester;

public class ValidatorManager {

	private static Validator validator = new Validator();
	private static Digester digester = null;

	static {
		digester = new Digester();
		digester.addObjectCreate("validator", Validator.class);
		digester.addSetProperties("validator", "resource-bundle", "resourceBundle");
		digester.addObjectCreate("validator/rule", Rule.class);
		digester.addSetProperties("validator/rule", "name", "name");
		digester.addSetProperties("validator/rule", "class", "clazz");
		digester.addSetProperties("validator/rule", "method", "method");
		digester.addSetProperties("validator/rule", "msg", "msg");
		digester.addSetProperties("validator/rule", "resource-bundle", "resourceBundle");
		digester.addSetNext("validator/rule", "addRule");
	}

	public static Rule findRule(String name) {
		return ValidatorManager.validator.getRules().get(name);
	}

	public static synchronized void addValidator(String configFile) throws Exception {
		if (!configFile.startsWith("/")) {
			configFile = "/" + configFile;
		}
		addValidator(ValidatorManager.class.getResourceAsStream(configFile));
	}

	public static synchronized void addValidator(InputStream configStream) throws Exception {
		Validator validator = ((Validator) digester.parse(configStream));
		for (Rule rule : validator.getRules().values()) {
			if(rule.getResourceBundle() == null || "".equals(rule.getResourceBundle())){
				rule.setResourceBundle(validator.getResourceBundle());	
			}
			ValidatorManager.validator.addRule(rule);
		}
	}
}